package top.todu.demo.spirngcloud.gateway.demo.config;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.*;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/** filter 名字为前缀 ，也就是 TcpService， GatewayFilterFactory 是固定后缀 */
@Component
@Slf4j
public class DubboServiceGatewayFilterFactory implements Ordered, GlobalFilter {

  @Override
  public int getOrder() {
    return Ordered.LOWEST_PRECEDENCE;
  }

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

    String scheme = requestUrl.getScheme();
    if (isAlreadyRouted(exchange) || (!"dubbo".equalsIgnoreCase(scheme))) {
      return chain.filter(exchange);
    }
    setAlreadyRouted(exchange);
    log.info("自定义：dubbo, isCommitted: {}", exchange.getResponse().isCommitted());
    exchange.getAttributes().put("targetSchema", "tcp");
    // 处理TCP服务的逻辑

    // 建立到TCP服务的连接,并发送请求数据
    byte[] requestData =
        "dubbo 从exchange中获取请求数据".getBytes(StandardCharsets.UTF_8); // 从exchange中获取请求数据
    byte[] responseData = "dubbo 从TCP服务中获取响应数据".getBytes(StandardCharsets.UTF_8); // 从TCP服务中获取响应数据
    // 将响应数据写回到exchange中
    // 将响应数据写回到exchange中
    ServerHttpResponse response = exchange.getResponse();
    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    Mono<Void> voidMono =
        response.writeWith(Mono.just(response.bufferFactory().wrap(responseData)));
    log.info("自定义：dubbo, isCommitted: {}", exchange.getResponse().isCommitted());
    return voidMono.then(chain.filter(exchange));
  }
}
